package com.zzyl.nursing.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.common.utils.http.HttpUtils;
import com.zzyl.nursing.service.WechatService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.net.http.HttpClient;
import java.util.HashMap;
import java.util.Map;


@Service
public class WechatServiceImpl implements WechatService {


    @Value("${wechat.appId}")
    private String appid;

    @Value("${wechat.appSecret}")
    private String appSecret;

    // 登录
    private static final String OPENID_URL = "https://api.weixin.qq.com/sns/jscode2session?grant_type=authorization_code";

    // 获取token
    private static final String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";

    // 获取手机号
    private static final String PHONE_REQUEST_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";


    @Override
    public String getOpenid(String code) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("appid", appid);
        paramMap.put("secret", appSecret);
        paramMap.put("js_code", code);
        String result = HttpUtil.get(OPENID_URL, paramMap);
        JSONObject jsonObject = JSONUtil.parseObj(result);
        // 判断接口响应是否出错
        if(ObjectUtil.isNotEmpty(jsonObject.getInt("errcode"))) {
            throw new RuntimeException(jsonObject.getStr("errmsg"));
        }
        else return jsonObject.getStr("openid");
    }

    public String getToken() {
        Map<String, Object> paramMap = Map.of("appid", appid, "secret", appSecret);
        String result = HttpUtil.get(TOKEN_URL, paramMap);
        JSON parse = JSONUtil.parse(result);
        if (parse.getByPath("access_token") != null){
            return parse.getByPath("access_token").toString();
        }
        else throw new RuntimeException("access_token未获取");
    }

    @Override
    public String getPhone(String detailCode) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("code", detailCode);
        String access_token = getToken();
        // 发起请求
        String result = HttpUtil.post(PHONE_REQUEST_URL+access_token, JSONUtil.toJsonStr(paramMap));
        JSONObject jsonObject = JSONUtil.parseObj(result);
        // 判断接口响应是否出错
        if(jsonObject.getInt("errcode") != 0) {
            throw new RuntimeException(jsonObject.getStr("errmsg"));
        }

        return jsonObject.getJSONObject("phone_info").getStr("phoneNumber");
    }
}
